package code.starivan.leetcode;

import java.util.HashMap;

/**
 * Created by Ivan on 2015/10/19.
 */
/*

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

        For example,
        S = "ADOBECODEBANC"
        T = "ABC"
        Minimum window is "BANC".

        Note:
        If there is no such window in S that covers all characters in T, return the empty string "".

        If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

        Show Tags
        Show Similar Problems


*/

public class N076_MinimumWindowSubstring {
    public static void test(){
        System.out.println(new N076_MinimumWindowSubstring().minWindow("aaa","aa"));
    }

    public String minWindow(String s, String t) {
        if(s==null||s.isEmpty()||t==null||t.isEmpty()){
            return "";
        }

        HashMap<Character,Integer> helpMap=new HashMap<>();
        HashMap<Character,Integer> countMap=new HashMap<>();

        for(int i=0;i<t.length();++i){
            char c=t.charAt(i);
            if(!helpMap.containsKey(c)){
                helpMap.put(c,0);
                countMap.put(c,1);
            }else{
                countMap.put(c,countMap.get(c)+1);
            }
        }

        int left=0,right=0,cur=0,minLength=Integer.MAX_VALUE,ml=-1,mr=-1;
        while (right<s.length()){
            char c=s.charAt(right);
            if(helpMap.containsKey(c)){
                if(helpMap.get(c)<countMap.get(c)){
                    cur++;
                }

                helpMap.put(c,helpMap.get(c)+1);
            }

            if(cur>=t.length()){
                while (cur>=t.length()){
                    char tmp=s.charAt(left);
                    if(helpMap.containsKey(tmp)){
                        if(helpMap.get(tmp)<=countMap.get(tmp)){
                            cur--;
                        }

                        helpMap.put(tmp,helpMap.get(tmp)-1);
                    }

                    left++;
                }


                if((right-left+2)<minLength){
                    minLength=right-left+2;
                    ml=left-1;
                    mr=right;
                }
            }

            right++;
        }

        if(ml!=-1){
            return s.substring(ml,mr+1);
        }else{
            return "";
        }
    }
}
